<template>
    <div class="app-container">
  
      <div class="filter-container">
      <!-- 主要搜索条件 -->
      <el-collapse v-model="activePanel" style="margin-bottom: 15px;">
        <el-collapse-item title="基础搜索条件" name="base">
          <div class="search-container">
            <div class="search-item">
              <span class="search-title">课程名称</span>
              <el-input size="small" v-model="name" placeholder="请输入课程名称" style="width: 200px"></el-input>
            </div>
            <div class="search-item">
              <span class="search-title">教练名称</span>
              <el-input size="small" v-model="coachName" placeholder="请输入教练名称" style="width: 200px"></el-input>
            </div>
            <div class="search-item">
              <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
          </div>
        </el-collapse-item>
  
        <!-- 高级搜索条件 -->
        <el-collapse-item title="高级搜索条件" name="advanced">
          <div class="search-container">
            <div class="search-item">
              <span class="search-title">开始时间</span>
              <el-date-picker
                v-model="startTime"
                type="datetime"
                placeholder="选择开始时间"
                size="small"
                style="width: 150px"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
            <div class="search-item">
              <span class="search-title">结束时间</span>
              <el-date-picker
                v-model="endTime"
                type="datetime"
                placeholder="选择结束时间"
                size="small"
                style="width: 150px"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
            <div class="search-item">
              <span class="search-title">时长</span>
              <el-input size="small" v-model="duration" placeholder="请输入课程时长" style="width: 150px"></el-input>
            </div>
            <div class="search-item">
              <span class="search-title">位置</span>
              <el-input size="small" v-model="location" placeholder="请输入课程位置" style="width: 150px"></el-input>
            </div>
            <div class="search-item">
              <span class="search-title">人数</span>
              <el-input size="small" v-model="maxCapacity" placeholder="请输入人数" style="width: 150px"></el-input>
            </div>
            <div class="search-item">
              <span class="search-title">课程状态</span>
              <el-select v-model="status" size="small" placeholder="请选择" style="width: 150px">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
  
      <!-- 右侧操作按钮 -->
      <div class="right-container">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">新增课程</el-button>
      </div>
    </div>
  
      <!-- 数据区域 -->
      <el-table :data="courses" style="width: 100%;" height="700">
        <el-table-column prop="name" align="center" label="课程名称"></el-table-column>
        <el-table-column prop="coachName" align="center" label="教练姓名"></el-table-column>
        <el-table-column prop="duration" label="时长" align="center"></el-table-column>
        <el-table-column prop="maxCapacity" label="最大人数" align="center"></el-table-column>
        <el-table-column prop="bookedCount" label="已预约人数" align="center"></el-table-column>
        <el-table-column prop="location" label="授课地址" align="center"></el-table-column>
        <el-table-column prop="schedule" label="开始时间" align="center"></el-table-column>
  
        <el-table-column prop="status" align="center" label="课程状态">
          <template slot-scope="scope">
            <span>{{ scope.row.status===1?'未开始':scope.row.status===2?'进行中':scope.row.status===3?'已完成':'已取消' }}</span>
          </template>
        </el-table-column>
  
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)">
              <i class="el-icon-edit" style="margin-right: -3px;"></i>
              编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              style="margin-right: 4px;"
              @click="handleConcel(scope.row)"
            >
              <i class="el-icon-delete" style="margin-right: -3px;"></i>
              取消课程
            </el-button>
            <el-dropdown size="mini">
              <el-button size="small" type="text">
                <i class="el-icon-d-arrow-right" style="margin-right: -5px;"></i>
                更多
              </el-button>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页区域 -->
      <el-pagination
        class="pagination-container"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
  
      <!-- 添加/编辑员工对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="500px"
        :before-close="handleClose"
      >
        <el-form
          :model="formData"
          class="addDialog"
          :rules="rules"
          ref="formRef"
          size="small"
          label-width="120px"
        >
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="教练" prop="coachId">
              <el-select v-model="formData.coachId" placeholder="请选择教练" style="width: 100%;">
                  <el-option
                  v-for="coach in coaches"
                  :key="coach.id"
                  :label="coach.name"
                  :value="coach.id">
                  </el-option>
              </el-select>
          </el-form-item>
  
          <el-form-item label="开始时间" prop="schedule">
              <el-date-picker
                  v-model="formData.schedule"
                  type="datetime"
                  placeholder="选择开始时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
          </el-form-item>
          
  
        <el-form-item label="课程状态" prop="status">
          <el-select v-model="statusLabel" placeholder="请选择课程状态" style="width: 100%;">
            <el-option
            v-for="option in statusFormOptions"
            :key="option.value"
            :label="option.label"
            :value="option.label">
            </el-option>
          </el-select>
        </el-form-item>
  
          <el-form-item label="课程时长" prop="duration">
            <el-input v-model="formData.duration"></el-input>
          </el-form-item>
          <el-form-item label="课程位置" prop="location">
            <el-input v-model="formData.location"></el-input>
          </el-form-item>
          <el-form-item label="最大人数" prop="maxCapacity">
            <!-- <el-input v-model="formData.maxCapacity"></el-input> -->
             <el-input-number v-model="formData.maxCapacity" />
          </el-form-item>
          
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 取消课程确认对话框 -->
      <el-dialog title="确认取消" :visible.sync="deleteDialogVisible" width="300px">
        <p align="center">确定要取消课程 {{ concelCourseName }} 吗？</p>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="handleConfirmConcel">确认取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
    
  <script>
  import {  addCourse , updateCourse, queryCourse} from "@/api/course";
  import { getAllCoachs } from "@/api/coach";
  import { deleteFile } from "@/api/common";
  export default {
    data() {
      return {
        uploadHeaders:{
          'X-Requested-With': 'XMLHttpRequest',
          'token': localStorage.getItem('token') || '',
        },
        uploadUrl: "/api/admin/common/upload",
        // 课程数据
        courses: [],
        //教练数据
        coaches: [],
  
  
        // 搜索筛选
        name: "",
        coachName: "",
        startTime: '',
        endTime: '',
        duration: null,
        location: "",
        maxCapacity: "",
        status: null,
        statusOptions: [
          { label: '全部', value: null },
          { label: '未开始', value: '1' },
          { label: '进行中', value: '2' },
          { label: '已完成', value: '3' },
          { label: '已取消', value: '0' },
        // 可根据实际情况添加更多状态
        ],
        statusFormOptions: [
          { label: '未开始', value: '1' },
          { label: '进行中', value: '2' },
          { label: '已完成', value: '3' },
          { label: '已取消', value: '0' },
        // 可根据实际情况添加更多状态
        ],
  
        // 分页
        currentPage: 1,
        pageSize: 10,
        total: 0,
  
        // 对话框
        dialogVisible: false,
        dialogType: "add", // 'add' 或 'edit'
        dialogTitle: "添加课程",
        formData: {
          name: "", // 课程名称
          coachId: null,//教练id
          schedule: "",//开始时间
          duration: null,//课程时长
          maxCapacity: null,//最大人数
          location: "", //上课位置
          status: null,
        },
  
        // 表单验证规则
      rules: {
          name: [
            { required: true, message: '请输入课程名称', trigger: 'blur' }
          ],
          coachId: [
            { required: true, type: 'number', message: '请输入有效的教练ID', trigger: 'blur' }
          ],
          schedule: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],
          duration: [
            { required: true, message: '请输入课程时长', trigger: 'blur' }
          ],
          location: [
            { required: true, message: '请输入课程位置', trigger: 'blur' }
          ],
          maxCapacity: [
            { required: true, type: 'number', message: '请输入有效的人数', trigger: 'blur' }
          ]
        },
  
        // 取消课程相关
        deleteDialogVisible: false,
        concelCourseId: "",
        concelCourseName: ""
      };
    },
  
    computed: {
    statusLabel: {
      get() {
        // 根据当前 formData.status 查找对应 label
        const option = this.statusFormOptions.find(opt => opt.value == this.formData.status);
        return option ? option.label : '';
      },
      set(newLabel) {
        const option = this.statusFormOptions.find(opt => opt.label === newLabel);
        this.formData.status = option ? option.value : null;
      }
    }
  },
    created() {
      // 在组件创建时加载教练列表
      this.loadCoaches();
      },
      
  
  
    methods: {
      // 分页
      handleSizeChange(newSize) {
        this.pageSize = newSize;
        this.handleSearch();
      },
  
      handleCurrentChange(newPage) {
        this.currentPage = newPage;
        this.handleSearch();
      },
  
      // 搜索
      handleSearch() {
          queryCourse({
              page: this.currentPage,
              pageSize: this.pageSize,
              name: this.name,
              coachName: this.coachName,
              startTime: this.startTime,
              endTime: this.endTime,
              duration: this.duration,
              location: this.location,
              maxCapacity: this.maxCapacity,
              status: this.status
          }).then(res => {
              const data = res.data.data;
              this.courses = data.records;
              this.total = data.total;
          })
      },
  
      // 添加员工
      handleAdd() {
        this.dialogType = "add";
        this.dialogTitle = "新增课程";
        this.dialogVisible = true;
      },
  
      // 编辑员工
      handleEdit(row) {
        this.dialogType = "edit";
        this.dialogTitle = "编辑课程";
        this.formData = { ...row }; // 复制对象，避免直接修改原数据
        this.dialogVisible = true;
      },
  
      //加载教练信息
      loadCoaches() {
          getAllCoachs().then(res=>{
              this.coaches = res.data.data;
          })
      },
  
      // 保存员工信息
      handleSave() {
        // 调用表单的验证方法
        this.$refs.formRef.validate(valid => {
          if (valid) {
            if (this.dialogType === "add") {
              // 添加新课程
              console.log(this.formData)
              addCourse(this.formData).then((res)=>{
                if(res.data.code===1){
                  this.$message.success("添加成功");
                  // 表格数据更新
                  this.handleSearch();
                }else{
                  this.$message.error(res.data.msg);
                }
              })
  
            } else {
              updateCourse(this.formData).then(res=>{ 
                  if(res.data.code===1){
                  this.$message.success("修改成功");
                  // 表格数据更新
                  this.handleSearch();
                }else{
                  this.$message.error(res.data.msg);
                }
              })
            }
            this.dialogVisible = false;
            
          } else {
            this.$message.error("请完善表单信息");
            return false;
          }
        });
      },
  
      // 关闭对话框
      handleClose(done) {
        // 如果添加头像了，需要删除
        if (this.formData.avatar) {
          deleteFile(this.formData.avatar)
        }
        // 表单数据重置
        this.$refs.formRef.resetFields();
        done();
      },
  
      // 取消课程
      handleConcel(row) {
        this.concelCourseId = row.id;
        this.concelCourseName = row.name;
        this.deleteDialogVisible = true;
      },
  
      // 确认删除
      handleConfirmConcel() {
          // 构造参数：id + status（逻辑删除值）
          const params = {
              id: this.concelCourseId,
              status: 0 // 0 表示已删除（根据你的业务定义）
          };
        updateCourse(params).then(res=>{
          if(res.data.code!==1){
            this.$message.error(res.data.msg)
          }else{
            this.$message.success("取消课程成功")
          }
          // 表格数据更新
          this.handleSearch();
        })
        this.deleteDialogVisible = false;
      }
    },
    mounted() {
      //初始化表格数据
      this.handleSearch();
    },
  
  };
  </script>
    
  <style lang="less" scoped>
  .app-container {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  
    .filter-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      margin-bottom: 10px;
  
      .search-container {
        display: flex;
  
        .search-item {
          margin-right: 10px;
  
          .search-title {
            line-height: 32px;
            padding: 0 12px 0 0;
            color: #606266;
            font-size: 14px;
            font-weight: 700;
          }
        }
      }
    }
  
    .addDialog /deep/ .el-input {
      width: 280px;
    }
  
    .addDialog {
      .avatar-uploader::v-deep .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
  
      .avatar-uploader::v-deep .el-upload:hover {
        border-color: #409eff;
      }
  
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;
      }
  
      .avatar {
        width: 80px;
        height: 80px;
        display: block;
      }
    }
  }
  </style>